<template>
  <div>
    <el-button type="primary" @click="downFile">下载</el-button>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import {
  Message,
  Loading
} from 'element-ui'
let downloadLoading;
export default {
  data () {
    return {
    };
  },
  created () { },
  computed: {},
  mounted () { },
  methods: {
    downFile () {
      this.download('http://localhost:6330/file/downFile', { name: 'tom', age: 20 }, '测试.xls')
    },
    download (url, params, filename) {
      downloadLoading = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
      return this.$axios.post(url, params, {
        // transformRequest: [(params) => { return JSON.stringify(params) }],
        // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        transformRequest: [(params) => { return JSON.stringify(params) }],
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        responseType: 'blob'
      }).then(async (res) => {
        const blob = new Blob([res.data])
        saveAs(blob, filename)
        downloadLoading.close();
      }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
        downloadLoading.close();
      })
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>